package cn.yunhe.dao.impl;

import cn.yunhe.dao.IEmpDao;
import cn.yunhe.eneity.Emp;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Component;

import java.sql.SQLException;
import java.util.List;

@Setter
@Getter
@Component
public class EmpDao extends HibernateDaoSupport implements IEmpDao {
    @Override
    public void addEmp(Emp emp) {
        getHibernateTemplate().save(emp);
    }

    @Override
    public void DelEmp(int empno) {
        getHibernateTemplate().delete(empno);
    }

    @Override
    public void updateEmp(Emp emp) {
        getHibernateTemplate().update(emp);
    }

    @Override
    public Emp get(int empno) {
        return getHibernateTemplate().get(Emp.class, empno);
    }

    @Override
    public List<Emp> searchEmp(final Emp emp) {
        List<Emp> list = getHibernateTemplate().executeFind(
                new HibernateCallback() {
                    @Override
                    public Object doInHibernate(Session session) throws HibernateException, SQLException {
                        Criteria cri = session.createCriteria(Emp.class);
                        if (emp != null) {
                            if (emp.getEname() != null && emp.getEname().trim().length() > 0) {
                                cri.add(Restrictions.like("ename", emp.getEname(), MatchMode.ANYWHERE));
                            }
                        }
                        return cri.list();
                    }
                }
        );
        return list;
    }

    @Override
    public List<Emp> searchEmp(String hql) {
        return getHibernateTemplate().find(hql);
    }
}
